package com.jeecg.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeecg.demo.entity.*;
import com.jeecg.demo.service.*;
import com.jeecg.demo.util.MD5;
import com.jeecg.demo.util.PopupDataBindUtil;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Title: Controller
 * @Description: ZHAOBIAOPMJY_BAOM
 * @author onlineGenerator
 * @date 2018-11-26 16:18:24
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/zhaobiaopmjyBaomController")
public class ZhaobiaopmjyBaomController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ZhaobiaopmjyBaomController.class);

    @Autowired
    private ZhaobiaopmjyBaomServiceI zhaobiaopmjyBaomService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private PopupDataBindUtil bindUtil;
    @Autowired
    private SettlementServiceI settlementServiceI;
    @Autowired
    private ZhaoBiaoBaoMingService zhaoBiaoBaoMingService;
    @Autowired
    private TraderServiceI traderServiceI;
    @Autowired
    private BzjOperatorServiceI bzjOperatorServiceI;

    /**
     * ZHAOBIAOPMJY_BAOM列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView("com/jeecg/zhaobiaopmjyBaom/zhaobiaopmjyBaomList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     //* @param user
     * @throws Exception
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(ZhaoBiaoBaoMingEntity zhaobiaobaoming, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) throws Exception {
        CriteriaQuery cq = new CriteriaQuery(ZhaoBiaoBaoMingEntity.class, dataGrid);
        // 查询条件组装器
        // 如果绑定报表数据，则更新排序格式，将新增的虚拟列改为原表中对应列
        dataGrid.setSort(dataGrid.getSort().replace("username", "userid"));

        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zhaobiaobaoming, request.getParameterMap());
        try {
            // 自定义追加查询条件
        }
        catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.zhaoBiaoBaoMingService.getDataGridReturn(cq, true);
        // 绑定非字典表数据
        bindUtil.BindDDName(dataGrid, "SYS_USER", "username", "userid", "userid", "username");

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 审核ZHAOBIAOPMJY_BAOM
     *
     //* @param ids
     * @return
     */
    @RequestMapping(params = "doVerify")
    @ResponseBody
    public AjaxJson doVerify(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "审核成功";
        ZhaobiaopmjyBaomEntity t = zhaobiaopmjyBaomService.get(
                ZhaobiaopmjyBaomEntity.class, zhaobiaopmjyBaom.getId());
        try {
            t.setZhuangt("1");
            zhaobiaopmjyBaomService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "审核失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * ZHAOBIAOPMJY_BAOM审核页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goVerify")
    public ModelAndView goVerify(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(zhaobiaopmjyBaom.getId())) {
            zhaobiaopmjyBaom = zhaobiaopmjyBaomService.getEntity(
                    ZhaobiaopmjyBaomEntity.class, zhaobiaopmjyBaom.getId());
            req
                    .setAttribute("action",
                            "zhaobiaopmjyBaomController.do?doVerify");
            req.setAttribute("zhaobiaopmjyBaomPage", zhaobiaopmjyBaom);
        }
        return new ModelAndView("com/jeecg/zhaobiaopmjyBaom/zhaobiaopmjyBaom-update");
    }

    /**
     * 删除ZHAOBIAOPMJY_BAOM
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        zhaobiaopmjyBaom = systemService.getEntity(
                ZhaobiaopmjyBaomEntity.class, zhaobiaopmjyBaom.getId());
        message = "删除成功";
        try {
            zhaobiaopmjyBaomService.delete(zhaobiaopmjyBaom);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除ZHAOBIAOPMJY_BAOM
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom = systemService.getEntity(ZhaobiaopmjyBaomEntity.class, Integer.parseInt(id));
                zhaobiaopmjyBaomService.delete(zhaobiaopmjyBaom);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加ZHAOBIAOPMJY_BAOM
     *
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        try {
            zhaobiaopmjyBaomService.save(zhaobiaopmjyBaom);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 更新ZHAOBIAOPMJY_BAOM
     *
     //* @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "更新成功";
        ZhaobiaopmjyBaomEntity t = zhaobiaopmjyBaomService.get(ZhaobiaopmjyBaomEntity.class, zhaobiaopmjyBaom.getId());

        try {
            String zhuangt = zhaobiaopmjyBaom.getZhuangt();
            //首先，判断是否已存在该报名保证金日志数据
            boolean bool = bzjOperatorServiceI.isExistBzjData(t.getPocode(),String.valueOf(t.getTraderid()),"1","0");
            if ("2".equals(zhuangt) && !bool) {
                Map<String, Object> map = new HashMap();
                TraderEntity trader = systemService.getEntity(TraderEntity.class, t.getTraderid());
                if (trader != null) {
                    String tradecode = trader.getTradecode();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    String time = sdf.format(date);
                    String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
                    Integer subectId = 315;
                    String tranferMoeny = Globals.SETTLEMENT_TRANFERMOENY;
                    Integer type = 0;
                    String demo = "报名保证金";
                    map.put("firmId", tradecode);
                    map.put("subectId", subectId);

                    //新增于2024-05-24
                    //tranferMoeny  =  bzjOperatorServiceI.operatorForBaomByConfig(t);
                    BzjOperatorLogEntity logEntity = bzjOperatorServiceI.operatorForBaomByConfig(t);
                    tranferMoeny = logEntity.getResult();

                    map.put("tranferMoeny", tranferMoeny);
                    map.put("transferTime", time);
                    map.put("sertalNo", uuid);
                    map.put("type", type);
                    map.put("demo", demo);
                    String params = JSON.toJSONString(map);
                    String methond = "freezeDeposit";

                    logger.info("发送报名冻结信息 ：" + params);
                    String result = settlementServiceI.doSettlement(params, methond);
                    if ("success".equals(result)) {
                        FreezeDepositEntity freezeDepositEntity = new FreezeDepositEntity();
                        freezeDepositEntity.setTraderCode(tradecode);
                        freezeDepositEntity.setSubectId(subectId);
                        freezeDepositEntity.setTranferMoeny(tranferMoeny);
                        freezeDepositEntity.setTransferTime(time);
                        freezeDepositEntity.setSertalNo(uuid);
                        freezeDepositEntity.setType(type);
                        freezeDepositEntity.setDemo(demo);
                        freezeDepositEntity.setStatus(1);
                        freezeDepositEntity.setPocode(t.getPocode());
                        systemService.save(freezeDepositEntity);

                        MyBeanUtils.copyBeanNotNull2Bean(zhaobiaopmjyBaom, t);
                        zhaobiaopmjyBaomService.saveOrUpdate(t);
                        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);

                        bzjOperatorServiceI.save(logEntity);
                    }
                    else {
                        message = "更新失败," + result;
                    }
                }
            }
            else {
                MyBeanUtils.copyBeanNotNull2Bean(zhaobiaopmjyBaom, t);
                zhaobiaopmjyBaomService.saveOrUpdate(t);
                systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
                message = "更新成功";
            }

            String mobile = "";
            String msg = "";
            String md5sourcenew = "";
            String excode = "";
            MD5 md5 = new MD5();
            String url = "http://119.39.227.245/api/sendtempletmsg";
            String key = "gpXZqXnW7zHTQAP8iiSaPSGGFAyPycrf";
            String cpid = "700137";
            String sql = " SELECT\n" +
                    "\txm.MOBILE\n" +
                    "FROM\n" +
                    "\tXM_MESSAGE xm\n" +
                    "WHERE\n" +
                    "\txm.ORGID = ? ";
            List<Map<String, Object>> listMap = systemService.findForJdbc(sql,t.getTraderid());
            String format = new SimpleDateFormat().format(new Date());
            for (Map<String, Object> maps : listMap) {
                mobile = maps.get("MOBILE").toString();
                msg = "【湖南省煤炭大数据中心】贵公司交易平台资金账户" + t.getFullname() + "于" +format+ "冻结账户内资金20000元，变动类型:保证金，关联订单号:"+t.getPocode();
                Map<String, Object> map = new HashMap<String, Object>();
                String md5source = cpid + msg + mobile + excode + key;
                map.put("cpid", cpid);
                map.put("msg", msg);
                map.put("excode", excode);
                map.put("mobiles", mobile);
                map.put("sign", DigestUtils.md5DigestAsHex(md5source.getBytes("UTF-8")).toLowerCase());
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<Map<String, Object>>(map, headers);
                ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JSONObject.class);
                JSONObject respJson = exchange.getBody();
                System.out.println(respJson.toString());
                String strjson = respJson.getString("resultcode");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * ZHAOBIAOPMJY_BAOM新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(zhaobiaopmjyBaom.getId())) {
            zhaobiaopmjyBaom = zhaobiaopmjyBaomService.getEntity(ZhaobiaopmjyBaomEntity.class, zhaobiaopmjyBaom.getId());
            req.setAttribute("zhaobiaopmjyBaomPage", zhaobiaopmjyBaom);
        }
        return new ModelAndView("com/jeecg/zhaobiaopmjyBaom/zhaobiaopmjyBaom-add");
    }

    /**
     * ZHAOBIAOPMJY_BAOM编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(zhaobiaopmjyBaom.getId())) {
            zhaobiaopmjyBaom = zhaobiaopmjyBaomService.getEntity(ZhaobiaopmjyBaomEntity.class, zhaobiaopmjyBaom.getId());
            req.setAttribute("zhaobiaopmjyBaomPage", zhaobiaopmjyBaom);
        }
        return new ModelAndView("com/jeecg/zhaobiaopmjyBaom/zhaobiaopmjyBaom-update");
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "zhaobiaopmjyBaomController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap, String ids) {
        CriteriaQuery cq = new CriteriaQuery(ZhaobiaopmjyBaomEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zhaobiaopmjyBaom, request.getParameterMap());
        cq.in("id", bindUtil.idsToIntegerArray(ids));
        cq.add();
        List<ZhaobiaopmjyBaomEntity> zhaobiaopmjyBaoms = this.zhaobiaopmjyBaomService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "ZHAOBIAOPMJY_BAOM");
        modelMap.put(NormalExcelConstants.CLASS, ZhaobiaopmjyBaomEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("ZHAOBIAOPMJY_BAOM列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, zhaobiaopmjyBaoms);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "ZHAOBIAOPMJY_BAOM");
        modelMap.put(NormalExcelConstants.CLASS, ZhaobiaopmjyBaomEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("ZHAOBIAOPMJY_BAOM列表", "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ZhaobiaopmjyBaomEntity> listZhaobiaopmjyBaomEntitys = ExcelImportUtil.importExcel(file.getInputStream(), ZhaobiaopmjyBaomEntity.class, params);
                for (ZhaobiaopmjyBaomEntity zhaobiaopmjyBaom : listZhaobiaopmjyBaomEntitys) {
                    zhaobiaopmjyBaomService.save(zhaobiaopmjyBaom);
                }
                j.setMsg("文件导入成功！");
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

}


